﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework.Content;

namespace Innovator
{
	public class IEContentManager : ContentManager
	{
		public IEContentManager(IServiceProvider serviceProvider)
			: base(serviceProvider) { }

		public bool PreserveAssets = true;
		//list of disposable assets
		List<IDisposable> disposable = new List<IDisposable>();
		Dictionary<string, object> loaded = new Dictionary<string, object>();
		//override loading of assets
		public override T Load<T>(string assetName)
		{
			T r = this.ReadAsset<T>(assetName, RecordIDisposable);
			if (PreserveAssets && !loaded.ContainsKey(assetName))
				loaded.Add(assetName, r);
			return r;
		}
		//internal method to record disposable assets
		void RecordIDisposable(IDisposable asset)
		{
			if (PreserveAssets)
				disposable.Add(asset);
		}
		//unload all content
		public override void Unload()
		{
			foreach (IDisposable disp in disposable)
				disp.Dispose();
			loaded.Clear();
			disposable.Clear();
		}
		//unload a spesific content
		public void Unload(string assetName)
		{
			if(loaded.ContainsKey(assetName))
			{
				if(loaded[assetName] is IDisposable && disposable.Contains((IDisposable)loaded[assetName]))
				{
					IDisposable obj = disposable[disposable.IndexOf((IDisposable)loaded[assetName])];
					obj.Dispose();
					disposable.Remove(obj);
				}
				loaded.Remove(assetName);
			}
		}
	}
}